package com.dinadi.yidi.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.ScrollView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by nolan on 2015/9/14.
 * Email：jy05892485@163.com
 */
public class BitmapMath {
    public static final int BITMAP_UPLOAD_WIDTH = 960;
    public static final int BITMAP_UPLOAD_HEIGHT = 720;

    public static final int OUT_OF_MEMORY = 5001;//内存溢出
    public static final int NOT_FOUND_IMAGE_FILE = 5002;//未找到文件

    /**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转图片
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotatingImageView(int angle, Bitmap bitmap) throws OutOfMemoryError {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    /**
     * 压缩图片分辨率
     * @param srcFilePath
     * @param outFilePath
     * @return
     */
    public static int compressBitmapPixels(String srcFilePath, String outFilePath){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inJustDecodeBounds = true;
        Bitmap image = BitmapFactory.decodeFile(srcFilePath, options);// 找到图片转换成bitmap并缩放至
        int height = options.outHeight;
        int width = options.outWidth;
        options.inSampleSize = 1;
        options.inJustDecodeBounds = false;
        float widthSizeF = 1;
        float heightSizF = 1;
        if( width > BITMAP_UPLOAD_WIDTH ){
            widthSizeF = ((float) width/(float) BITMAP_UPLOAD_WIDTH);
        }
        if(width > BITMAP_UPLOAD_HEIGHT){
            heightSizF = ((float) height/(float) BITMAP_UPLOAD_HEIGHT);
        }
        float max = Math.max(widthSizeF,heightSizF);

        options.inSampleSize = (int) (max+0.5);
        try {
            File file = new File(srcFilePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            image = BitmapFactory.decodeStream(fileInputStream, null, options);// 找到图片转换成bitmap并缩放至
        } catch (OutOfMemoryError e) {
            return OUT_OF_MEMORY;
        } catch (FileNotFoundException e) {
            return NOT_FOUND_IMAGE_FILE;
        }
//        Log.d("zoom", "srcH:" + height + "-srcW:" + width + "-zoom:" + options.inSampleSize + "-H:" + image.getHeight() + "-W" + image.getWidth());

        //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
//        Bitmap image = BitmapFactory.decodeFile(filePath);
        if (image != null) {
            //判断图片旋转并纠正
            int degree = readPictureDegree(srcFilePath);
            Bitmap rotatedImage = null;
            try {
                rotatedImage = rotatingImageView(degree, image);
                int quality = 100;
                FileOutputStream out = new FileOutputStream(outFilePath);
                if (rotatedImage.compress(Bitmap.CompressFormat.JPEG, quality, out)) {
                    out.flush();
                    out.close();
                }

            } catch (Exception e) {
            } catch (OutOfMemoryError e){
                return OUT_OF_MEMORY;
            }finally {
                if(image!=null)
                    image.recycle();
                if(rotatedImage!=null)
                    rotatedImage.recycle();
            }
        }
        return 0;
    }

    /**
     * 从URI获取到路径
     * @param context
     * @param uri
     * @return
     */
    public static String getPathForUri(Context context, Uri uri){
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
    
    public static byte[] compressBitmap(Bitmap bitBitmap, int maxBuffSize){
		byte[] bitBuff = null;
		Bitmap bitmap = null;
		try {
			if (bitBitmap != null && !bitBitmap.isRecycled()) {
				int count = 100;
				bitBuff = bitmapCompress(bitBitmap, count);
				if(bitBuff != null){
					while(bitBuff.length > maxBuffSize && count >=10){
						count = count -10;
						bitBuff = bitmapCompress(bitBitmap, count);
					}
					//Log.i("bitBuff:"+bitBuff.length+"------count:"+count);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		} finally {
			if (null != bitmap && !bitmap.isRecycled()) {
				bitmap.recycle();
			}
			if (null != bitBitmap && !bitBitmap.isRecycled()) {
				bitBitmap.recycle();
			}
		}

		return bitBuff;
	}
    
    public static byte[] bitmapCompress(Bitmap bitmap, int quality)
			throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = null;
		try {
			bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
			b = baos.toByteArray();
		} finally {
			try {
				if (null != baos) {
					baos.close();
				}
			} catch (Exception e) {

			}
		}
		return b;
	}
    
    /**
	 * 截屏方法
	 * 
	 * @return
	 */
	public static boolean getBitmapByView(ScrollView scrollView, String path) {
		int h = 0;
		Bitmap bitmap = null;
		// 获取listView实际高度
		for (int i = 0; i < scrollView.getChildCount(); i++) {
			h += scrollView.getChildAt(i).getHeight();
		}
		// 创建对应大小的bitmap
		bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.ARGB_8888);
		final Canvas canvas = new Canvas(bitmap);
		scrollView.draw(canvas);
		byte[] buff = compressBitmap(bitmap, 1024*1024*2);
		if(buff != null){
			// 测试输出
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(path);
				out.write(buff);
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}else{
			return false;
		}
		if(bitmap != null && !bitmap.isRecycled()){
			bitmap.recycle();
		}
		return true;
	}
}
